<template>
  <div>
    <nav-bar>
      <template v-slot:default>分类页面</template>
    </nav-bar>
    <div id="mainbox">
      <div class="ordertab">
        <van-tabs v-model="active" @click="tabClick">
          <van-tab title="销量排序"></van-tab>
          <van-tab title="价格排序"></van-tab>
          <van-tab title="评论排序"></van-tab>
        </van-tabs>
      </div>
      <van-sidebar v-model="activeKey"  class="leftmenu">
        <van-collapse v-model="activeName" accordion>
          <van-collapse-item v-for="item in categories"
                             :key="item.id"
                             :title="item.name"
                             :name="item.name">
            <van-sidebar-item v-for="sub in item.children"
                              :key="sub.id"
                              :title="sub.name"
                              @click = "getGoods(sub.id)"
            />
          </van-collapse-item>
        </van-collapse>
      </van-sidebar>
      <div class="goodslist">
        <div class="content">
          <van-card
              v-for="item in showGoods"
              @click = "itemClick(item.id)"
              :key="item.id"
              :tag="item.comments_count >= 0 ? '流行' : '标签' "
              :num="item.sales"
              :price="item.price"
              :desc="item.updated_at"
              :title="item.title"
              :thumb="item.cover_url"
              :lazy-load="true"
          />
        </div>
      </div>
    </div>
    <back-top @bTop="bTop" v-show="isShowBackTop"></back-top>
  </div>
</template>

<script>
import NavBar from "components/common/navbar/NavBar";
import {getCategory,getCategoryGoods} from "network/category";
import {ref, onMounted, reactive, computed, watchEffect, nextTick} from 'vue';
import {useRouter} from 'vue-router';
import BackTop from "components/common/backtop/BackTop";
import BScroll from "better-scroll";
export default {
  name: "Categroy",
  setup(){
    let activeKey = ref(0);
    let categories = ref([]);
    let activeName = ref(1);
    let active = ref(1);
    //当前的排序条件
    let currentOrder = ref('sales');
    //当前的分类ID
    let currentCid = ref(0);
    let bsrcoll = reactive({});
    let isShowBackTop = ref(false);
    let router = useRouter();
    onMounted(()=>{
      getCategory().then(res=>{
        categories.value = res.categories;
      })
      init();
      //创建BtterSrcoll对象
      bsrcoll = new BScroll(document.querySelector('.goodslist'),{
        //当 probeType 为 1 的时候，会非实时（屏幕滑动超过一定时间后）派发scroll 事件；
        // 当 probeType 为 2 的时候，会在屏幕滑动的过程中实时的派发 scroll 事件；
        // 当 probeType 为 3 的时候，不仅在屏幕滑动的过程中，而且在 momentum 滚动动画运行过程中实时派发 scroll 事件。
        // 如果没有设置该值，其默认值为 0，即不派发 scroll 事件。
        probeType:3,
        click:true,//是否允许点击
        pullUpLoad:true//上拉加载更多，默认false
      })
      //触发滚动事件
      bsrcoll.on('scroll',(position)=>{
        isShowBackTop.value = (-position.y)  > 300;
      });
      //上拉触发事件 pullingUp
      bsrcoll.on('pullingUp',()=>{
        console.log('上拉加载更多');
        const page = goods[currentOrder.value].page + 1;
        getCategoryGoods(currentOrder.value,currentCid.value).then(res=>{
          goods[currentOrder.value].list.push(...res.goods.data);
          goods[currentOrder.value].page += 1;
        })
        //完成上拉 等新数据加载完成 展示出来
        bsrcoll.finishPullUp();
        //重新计算高度
        nextTick(()=>{
          //重新计算高度
          bsrcoll && bsrcoll.refresh();//刷新
        })
        console.log('当前类型' + currentOrder.value + '，当前页:' + page);
        console.log('contentheight:'+document.querySelector('.content').clientHeight);
      })
    })
    //数据模型
    const goods = reactive({
      sales:{page:1,list:[]},
      price:{page:1,list:[]},
      comments_count:{page:1,list:[]},
    })
    const showGoods = computed(()=>{
      return goods[currentOrder.value].list;
    })

    const init = ()=>{
      getCategoryGoods('sales',currentCid.value).then(res=>{
        goods.sales.list = res.goods.data;
      })
      getCategoryGoods('price',currentCid.value).then(res=>{
        goods.price.list = res.goods.data;
      })
      getCategoryGoods('comments_count',currentCid.value).then(res=>{
        goods.comments_count.list = res.goods.data;
      })
    }
    //排序选项卡
    const tabClick = (index)=>{
      let orders = ['sales','price','comments_count']
      currentOrder.value = orders[index];
      getCategoryGoods(orders[currentOrder.value],currentCid.value).then(res=>{
        goods[currentOrder.value].list = res.goods.data;
        nextTick(()=>{
          //重新计算高度
          bsrcoll && bsrcoll.refresh();//刷新
        })
      })
      console.log("当前分类id: "+currentCid.value);
      console.log("排序的序号："+currentOrder.value);
    }
    //通过分类获取商品
    const getGoods = (cid)=>{
      currentCid.value = cid;
      init();
      console.log("当前分类id: "+currentCid.value);
      console.log("排序的序号："+currentOrder.value);
    }
    //监听任何一个有变化的变量
    watchEffect(()=>{
      nextTick(()=>{
        //重新计算高度
        bsrcoll && bsrcoll.refresh();//刷新
      })
    })
    //回到顶部
    const bTop = ()=>{
      bsrcoll.scrollTo(0,0,500);
    }
    return{
      activeKey,
      categories,
      activeName,
      active,
      tabClick,
      getGoods,
      goods,
      showGoods,
      bsrcoll,
      isShowBackTop,
      bTop,
      itemClick:(id)=>{
        router.push({path:'/detail',query:{id}})
      }
    }
  },
  components:{
    NavBar,
    BackTop
  }
}
</script>

<style scoped lang="scss">
#mainbox {
  margin-top: 45px;
  display: flex;
  .ordertab {
    flex: 1;
    float:right;
    height:50px;
    z-index: 9;
    position: fixed;
    top:45px;
    right:0;
    left:130px;
  }

  .leftmenu {
    position: fixed;
    top:95px;
    left:0;
    width:130px;
  }

  .goodslist {
    flex:1;
    position: absolute;
    top:100px;
    left:130px;
    right:0;
    height:100vh;
    padding:10px;
    text-align: left !important;
    .content {
    }
  }
}
#mainbox .ordertab{
  overflow: hidden;
}
.van-card__thumb {
  width:68px !important
}
</style>